package com.bank.manage.service.Impl;

import com.alibaba.fastjson2.JSON;
import com.bank.manage.enumerate.BankRedisKey;
import com.bank.manage.enumerate.BankStatus;
import com.bank.manage.enumerate.EventType;
import com.bank.manage.model.BankAccessWalletRecord;
import com.bank.manage.model.param.BankQueryParam;
import com.bank.manage.model.param.FaceRecordParam;
import com.bank.manage.model.vo.FaceRecordVo;
import com.bank.manage.service.BankAccessWalletRecordService;
import com.bank.manage.service.FaceRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.gavin.core.exception.ParamException;
import org.gavin.core.utils.IdUtils;
import org.redis.service.RedisService;
import org.springframework.stereotype.Service;

/**
 * FaceRecordServiceImpl
 *
 * @author grl
 * @date 2024/4/17
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FaceRecordServiceImpl implements FaceRecordService {

    private final RedisService redisService;
    private final BankAccessWalletRecordService bankAccessWalletRecordService;

    @Override
    public FaceRecordVo faceRecord(FaceRecordParam param) {
        checkParam(param);
        BankQueryParam queryParam = new BankQueryParam();
        queryParam.setRequestId(param.getRequestId());
        queryParam.setWalletNum(param.getWalletNum());
        BankAccessWalletRecord bankAccess = bankAccessWalletRecordService.queryUserNum(queryParam);
        // 校验人脸是否一致 demo 暂时做不了
        assertResource(bankAccess);
        String specificValue = getSpecificValue(param, bankAccess);
        FaceRecordVo vo = new FaceRecordVo();
        vo.setSpecificValue(specificValue);
        log.error("人脸比对信息 {},{} 生成人脸唯一值 {}",param.getPid(), JSON.toJSONString(param),specificValue);
        return vo;
    }

    private String getSpecificValue(FaceRecordParam param, BankAccessWalletRecord bankAccess) {
        while (true){
            String specificValue = IdUtils.fastSimpleUUID();
            BankRedisKey specificValueKey = BankRedisKey.WALLET_VERIFICATION_SPECIFIC.joinKey(bankAccess.getUserNum(), param.getEventType(),specificValue);
            Boolean aBoolean = redisService.ifAbsent(specificValueKey);
            if(aBoolean){
                return specificValue;
            }
        }
    }

    private void assertResource(BankAccessWalletRecord bankAccess) {
        if (bankAccess == null) {
            throw ParamException.le(BankStatus.REQUEST_DATA_NOT_EXIST);
        }
    }

    private void checkParam(FaceRecordParam param){
        String eventType = param.getEventType();
        if(!EventType.SYS.equals(EventType.valueOf(eventType))){
            if(StringUtils.isBlank(param.getWalletNum())){
               throw ParamException.le(BankStatus.WALLET_NUM_PARAM_EMPTY);
            }
        }
    }
}
